<template>
  <el-main style="padding: 5px 10px 5px 10px;background-color: #F3F3F4">

    <el-card shadow="always"  body-style="padding: 10px;" style="margin-top: 10px">
      <span class="sub-title">输入昵称：</span>
      <el-input v-model="search" placeholder="请输入内容" style="width:15%"  size="small" clearable></el-input>  <!--clearable:用来清空输入框-->
      <el-button type="primary" style="margin-left:5px;" size="mini" @click="load()">搜索</el-button>
      <!--  这里的模糊查询是根据昵称进行模糊查询的  -->
    </el-card>

    <el-card shadow="always"  body-style="padding: 10px;" style="margin-top: 10px">
      <!--按钮区域    -->
      <div style="margin:5px">
        <el-button type="primary" size="mini" @click="add">新增</el-button>
      </div>
      <!-- 列表区-->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column prop="id" sortable label="ID"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="nickName" label="昵称"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <span v-if="scope.row.role === 1">管理员</span>
            <span v-if="scope.row.role === 2">普通用户</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column fixed="right" label="操作" width="260">
          <template #default="scope">
            <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
            <span> | </span>
            <!--handleEdit是编辑方法，后面有对应的方法-->
            <!-- 自带提示框的删除按钮 -->
            <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-link size="mini" type="danger">删除</el-link>   <!-- 注意此处如果方法加在删除按钮上，那么在弹出提示框点击确定的时候就无法执行删除操作了，
                所以这里需要将删除的方法，挂到弹框的确定按钮上 -->
              </template>
            </el-popconfirm>
          </template>

        </el-table-column>
      </el-table>
      <!--列表分页-->
      <div style="margin: 10px 0">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"> //双引号里面的total是定义一个变量，在这里定义了，就需要在下面data里面初始化一下
        </el-pagination>

        <el-dialog :title="title" v-model="dialogVisible" width="30%">
          <el-form :model="user" label-width="120px">
            <el-form-item label="姓名:">
              <el-input v-model="user.username" style="width:80%"></el-input>
            </el-form-item>
            <el-form-item label="用户头像:">
              <el-upload
                  class="avatar-uploader"
                  action="/api/sys/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">

                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item label="昵称:">
              <el-input v-model="user.nickName" style="width:80%"></el-input>
            </el-form-item>

            <el-form-item label="年龄:">
              <el-input v-model="user.age" style="width:80%"></el-input>
            </el-form-item>

            <el-form-item label="性别:">
              <el-radio v-model="user.sex" label="男">男</el-radio>
              <el-radio v-model="user.sex" label="女">女</el-radio>
            </el-form-item>

            <el-form-item label="地址:">
              <el-input type="textarea" v-model="user.address" style="width:80%"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
          </template>
        </el-dialog>
      </div>
    </el-card>

  </el-main>
</template>

<script>
import request from "../utils/request";

export default {
  name: 'user',
  components: {},
  data() {
    return {
      title: '',
      user: {url:""},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      pageSize: 5,
      total: 0,  //默认10条
      tableData: [],
      imageUrl: '',

    }
  },

  //页面加载完立即执行的方法
  created() {
    this.load()
  },


  computed: {

    uploadDisabled:function() {
      return this.fileList.length >0
    },

  },
  methods: {
    //查询方法
    load() {
      request.get("/user/selectList", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search
        }
      }).then(res => {
        debugger
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    //新增打开弹窗方法
    add() {
      this.dialogVisible = true;
      this.title = "新增"
      this.user = {}; //清空表单中的值
    },

    //进行保存 使用aios进行数据交互
    save() {
      if (this.user.id) {   //如果有id,则进行更新操作  并且更新使用put请求
        request.put("/user/update", this.user).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "修改成功"
            })
          } else {
            this.$message({
              type: "error",
              message: "修改失败"
            })
          }
          this.load();  //更新完成后，重新刷新表格数据
          this.dialogVisible = false;    //最后关闭弹窗

        })
      } else {     //如果没有id,则进行新增操作
        request.post("/user/save", this.user).then(res => {
          this.$message({
            type: "success",
            message: res.msg
          })
          this.load();  //更新完成后，重新刷新表格数据
          this.dialogVisible = false;    //最后关闭弹窗
        })
      }


    },

    //编辑打开弹窗方法
    handleEdit(row) {
      this.user = JSON.parse(JSON.stringify(row));  //将编辑的弹窗附上值
      this.dialogVisible = true;  //打开编辑的弹窗（和新增用的一个弹窗）
      this.title = "编辑"
    },


    //删除方法
    handleDelete(id) {
      request.delete("/user/del/" + id).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: "删除成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load()
      })
    },


    //在上面的data中，pageSize和currentPaage都有默认值，这里要触发分页，需要重新根据变量赋值
    //改变当前每页条数触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },

    //改变当前页码触发
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },



    //上传成功
    handleAvatarSuccess(res, file) {
      debugger
      //this.imageUrl = URL.createObjectURL(file.raw)
      console.log("自带的返回...."+this.imageUrl)
      console.log("我是手动返回..."+res.data)
      this.imageUrl = "/api"+res.data;
    },


    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },



  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 24px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>
